import * as utils from '../utils'

function createCourse16 (gl: WebGLRenderingContext) {
  gl.clearColor(0.0, 0.0, 0.0, 1.0)
  gl.clear(gl.COLOR_BUFFER_BIT)

  const vectexShaderSrc = `
  attribute vec4 a_Position;
  attribute vec2 a_UV;
  varying vec2 v_UV;
    void main() {
        gl_Position = a_Position;
        v_UV = a_UV;
    }
  `

  const fragmentShaderSrc = `
    precision mediump float;
    uniform sampler2D u_Sampler;
    varying vec2 v_UV;
      void main() {
          gl_FragColor = texture2D(u_Sampler, v_UV);
      }
    `

  const program = utils.initShaders(gl, vectexShaderSrc, fragmentShaderSrc)

  const vertices = new Float32Array([
    -0.5, 0.5, -0.3, 1.7,
    -0.5, -0.5, -0.3, -0.2,
    0.5, 0.5, 1.7, 1.7,
    0.5, -0.5, 1.7, -0.2
  ])
  const aPosition = gl.getAttribLocation(program, 'a_Position')
  const aUV = gl.getAttribLocation(program, 'a_UV')

  const vectexBuffer = gl.createBuffer()
  gl.bindBuffer(gl.ARRAY_BUFFER, vectexBuffer)
  gl.bufferData(gl.ARRAY_BUFFER, vertices, gl.STATIC_DRAW)

  const FSIZE = vertices.BYTES_PER_ELEMENT
  gl.vertexAttribPointer(aPosition, 2, gl.FLOAT, false, FSIZE * 4, 0)
  gl.enableVertexAttribArray(aPosition)

  gl.vertexAttribPointer(aUV, 2, gl.FLOAT, false, FSIZE * 4, FSIZE * 2)
  gl.enableVertexAttribArray(aUV)

  const texture = gl.createTexture()
  const uSampler = gl.getUniformLocation(program, 'u_Sampler')

  loadTexture()
  function loadTexture () {
    const image = new Image()

    image.src = 'https://vue-three.oss-cn-shanghai.aliyuncs.com/images/sky_cloud.jpg'
    // webgl为了安全设置了 图片跨域
    image.crossOrigin = ''
    image.onload = function () {
      gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1)

      gl.activeTexture(gl.TEXTURE0)
      gl.bindTexture(gl.TEXTURE_2D, texture)

      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR)
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE)
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT)
      gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGB, gl.RGB, gl.UNSIGNED_BYTE, image)

      gl.uniform1i(uSampler, 0)

      gl.clear(gl.COLOR_BUFFER_BIT)

      gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4)
    }
  }
}

export {
  createCourse16
}
